import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../providers/auth_provider_web.dart'; // 使用Web专用的认证提供者
import '../../widgets/platform/adaptive_button.dart';
import '../../widgets/platform/adaptive_text_field.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../../core/platform/platform_detector.dart';

/// Web专用登录页面（仅支持在线登录）
class LoginPageWeb extends ConsumerStatefulWidget {
  const LoginPageWeb({super.key});

  @override
  ConsumerState<LoginPageWeb> createState() => _LoginPageWebState();
}

class _LoginPageWebState extends ConsumerState<LoginPageWeb> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _obscurePassword = true;

  @override
  void initState() {
    super.initState();
    // 默认填入测试账号和密码
    _usernameController.text = 'admin';
    _passwordController.text = 'flowplan123';
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final authState = ref.watch(authStateProviderWeb);

    // 监听认证状态变化
    ref.listen<AuthStateWeb>(authStateProviderWeb, (previous, next) {
      if (next is AuthSuccessWeb) {
        // 登录成功，跳转到仪表板页面
        context.go('/dashboard');
      } else if (next is AuthErrorWeb) {
        // 显示错误信息
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: SelectableText(next.message),
            backgroundColor: Colors.red,
          ),
        );
      }
    });

    return Scaffold(
      body: SafeArea(
        child: LayoutBuilder(
          builder: (context, constraints) {
            // 根据平台调整布局
            if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
              return _buildDesktopLayout(context, authState);
            } else {
              return _buildMobileLayout(context, authState);
            }
          },
        ),
      ),
    );
  }

  Widget _buildMobileLayout(BuildContext context, AuthStateWeb authState) {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(24.0),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // Logo区域
              _buildLogo(),
              const SizedBox(height: 48),

              // 标题
              SelectableText(
                'FlowPlan',
                style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                      color: Theme.of(context).primaryColor,
                    ),
              ),
              const SizedBox(height: 8),
              SelectableText(
                '需求全生命周期智能管理平台112',
                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                      color: Colors.grey[600],
                    ),
              ),
              const SizedBox(height: 24),

              // 用户名输入框
              AdaptiveTextField(
                controller: _usernameController,
                labelText: '用户名',
                prefixIcon: Icons.person,
                hintText: '请输入用户名',
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  if (value.length < 3) {
                    return '用户名长度不能少于3位';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 密码输入框
              AdaptiveTextField(
                controller: _passwordController,
                obscureText: _obscurePassword,
                labelText: '密码',
                prefixIcon: Icons.lock,
                hintText: '请输入密码',
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscurePassword ? Icons.visibility : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      _obscurePassword = !_obscurePassword;
                    });
                  },
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  if (value.length < 6) {
                    return '密码长度不能少于6位';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 32),

              // 登录按钮
              AdaptiveButton(
                onPressed: authState is AuthLoadingWeb ? null : _handleLogin,
                isLoading: authState is AuthLoadingWeb,
                child: const SelectableText('登录'),
              ),
              const SizedBox(height: 24),

              // 注册链接
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SelectableText('没有账户？'),
                  TextButton(
                    onPressed: () => context.push('/register'),
                    child: const SelectableText('立即注册'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDesktopLayout(BuildContext context, AuthStateWeb authState) {
    final maxWidth = MediaQuery.of(context).size.width * 0.4;

    return Center(
      child: SingleChildScrollView(
        child: ConstrainedBox(
          constraints: BoxConstraints(maxWidth: maxWidth),
          child: Padding(
            padding: const EdgeInsets.all(32.0),
            child: AdaptiveCard(
              child: Form(
                key: _formKey,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // Logo区域
                    _buildLogo(),
                    const SizedBox(height: 48),

                    // 标题
                    SelectableText(
                      'FlowPlan',
                      style:
                          Theme.of(context).textTheme.headlineLarge?.copyWith(
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).primaryColor,
                              ),
                    ),
                    const SizedBox(height: 16),
                    SelectableText(
                      '需求全生命周期智能管理平台323',
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                            color: Colors.grey[600],
                          ),
                    ),
                    const SizedBox(height: 24),

                    // 用户名输入框
                    AdaptiveTextField(
                      controller: _usernameController,
                      labelText: '用户名',
                      prefixIcon: Icons.person,
                      hintText: '请输入用户名',
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入用户名';
                        }
                        if (value.length < 3) {
                          return '用户名长度不能少于3位';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 24),

                    // 密码输入框
                    AdaptiveTextField(
                      controller: _passwordController,
                      obscureText: _obscurePassword,
                      labelText: '密码',
                      prefixIcon: Icons.lock,
                      hintText: '请输入密码',
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscurePassword
                              ? Icons.visibility
                              : Icons.visibility_off,
                        ),
                        onPressed: () {
                          setState(() {
                            _obscurePassword = !_obscurePassword;
                          });
                        },
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入密码';
                        }
                        if (value.length < 6) {
                          return '密码长度不能少于6位';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 48),

                    // 登录按钮
                    AdaptiveButton(
                      onPressed:
                          authState is AuthLoadingWeb ? null : _handleLogin,
                      isLoading: authState is AuthLoadingWeb,
                      width: double.infinity,
                      child: const SelectableText('登录'),
                    ),
                    const SizedBox(height: 32),

                    // 注册链接
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const SelectableText('没有账户？'),
                        TextButton(
                          onPressed: () => context.push('/register'),
                          child: const SelectableText('立即注册'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLogo() {
    return Container(
      width: 80,
      height: 80,
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.circular(20),
      ),
      child: const Icon(
        Icons.dashboard,
        color: Colors.white,
        size: 40,
      ),
    );
  }

  void _handleLogin() {
    if (_formKey.currentState!.validate()) {
      // 调用Web专用的登录方法，传入用户名和密码
      ref.read(authStateProviderWeb.notifier).login(
            _usernameController.text.trim(),
            _passwordController.text.trim(),
          );
    }
  }
}
